var shell={
	name:"shell",
	promptStr:"vShell:/home/vShell$",
	currDir:["","home","vShell"],
	isDataLoad:false
};

//初始化方法
shell.initCtx=function(){
	if(!shell.isDataLoad){
		//加载数据文件
		$.get("./data/linux.data",{},function(data){
			$(".systemData").append(data);
			shell.isDataLoad=true;
			},"html"); 
	}	
};

//获取绝对路径，用数组表示
shell.getPath=function(filePath){
	if(typeof filePath=="undefined"||filePath=="") return null;
	var filePathArray=filePath.split(/\//);
	if(filePathArray.length>0){
		var realPath=[];
		var firstFile=filePathArray[0];
		if(""==firstFile){
			realPath.push(firstFile);
		}else if(/^\.$/.test(firstFile)){
			realPath=realPath.concat(shell.currDir);
		}else if(/^\.{2}$/.test(firstFile)){
			realPath=realPath.concat(shell.currDir);
			realPath.pop();
		}else if(/^\w+$/.test(firstFile)){
			realPath=realPath.concat(shell.currDir);
			realPath.push(firstFile);
		}else{
			realPath.push(firstFile);
		}
		
		for(var i=1;i<filePathArray.length;i++){
			if(/^\.$/.test(filePathArray[i])){
				continue;
			}else if(/^\.{2}$/.test(filePathArray[i])){
				realPath.pop();
			}else{
				realPath.push(filePathArray[i]);
			}
		}
		return realPath;
	}
};

//获取文件对象
shell.getFile=function(realPath){
	if(typeof realPath!="undefined"){
		var xPath=".systemData>linux>fileSystem>";
		for(var i=1;i<realPath.length;i++){
			xPath+="file[type='dir'][name='"+realPath[i]+"']>";
		}
		return $(xPath.substr(0,xPath.length-1));
	}
};

//判断文件是否存在
shell.isFileExist=function(realPath){
	if(typeof realPath!="undefined"){
		var xFile=shell.getFile(realPath);
		if(xFile.length>0){
			return true;
		}
	}
	return false;
};


//命令处理器
shell.commandHandle={
	cd:function(params){
		if(params.length>0){
			var path=params[0];
			var realPath=shell.getPath(path);
			if(realPath.length>0){
				if(shell.isFileExist(realPath)){
					shell.currDir=realPath;
					shell.promptStr=realPath.length==1?"vShell:/$":"vShell:"+realPath.join("/")+"$";
				}else{
					vShell.showInfo(path+":没有那个文件或目录");
				}
			}
		}
		vShell.setEditAndFocus(shell.promptStr);
		return false;
	}
};

//按键事件监听
shell.keyDownHandle=function(event){
		if(event.keyCode==13){
		/*
		 * 回车键
		 */
		var command=vShell.getInput();
		vShell.showInfo(command);
		command=command.replace(shell.promptStr,"");
		if("exit"!=command){
			var cmdArray=command.split(/\s+/);
			var cmdName=cmdArray.shift();
			var cmdParams=cmdArray;
			if(typeof shell.commandHandle[cmdName]=='function'){
				return shell.commandHandle[cmdName](cmdParams);
			}else{
				vShell.showInfo(""+cmdName+": 未找到命令");
				vShell.setEditAndFocus(shell.promptStr);
				return false;
			}
		}else{
			vShell.currCtx=null;
			vShell.setEditAndFocus(vShell.promptStr);
		}
		
		return false;
	}else if(event.keyCode==8){
		/*
		 * 删除键
		 */
		if(vShell.getInput()==shell.promptStr){
			return false;
		}
	}	
};
